package cn.edu.seu.cose.qol.ws.resource.util;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.restlet.ext.xml.DomRepresentation;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;

public class DomRepresentationBuilder {
	
	private static DomRepresentationBuilder _instance;
	
	public static DomRepresentationBuilder getInstance() {
		if (_instance == null) {
			_instance = new DomRepresentationBuilder();
		}
		
		return _instance;
	}
	
	protected DomRepresentationBuilder() {}
	
	public DomRepresentation getRepresentation(Object obj)
			throws JAXBException, IOException, SAXException,
			ParserConfigurationException {
		Writer stringWriter = new StringWriter();
		
		JAXBContext jaxbContext = JAXBContext.newInstance(obj.getClass());
		Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
		jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,
				true);
		jaxbMarshaller.marshal(obj, stringWriter);
		
		stringWriter.close();
		
		String xmlString = stringWriter.toString();
		DocumentBuilderFactory docBuilderFactory =
				DocumentBuilderFactory.newInstance();
		DocumentBuilder docBuilder =
				docBuilderFactory.newDocumentBuilder();
		Document outputDocument = docBuilder.parse(
				new ByteArrayInputStream(
						xmlString.getBytes()));
		
		DomRepresentation outputRepresentation =
				new DomRepresentation();
		outputRepresentation.setDocument(outputDocument);
		return outputRepresentation;
	}

}
